package com.xmmj.common.refresh

import android.annotation.SuppressLint
import android.content.Context
import android.text.TextUtils
import android.util.AttributeSet
import android.view.View
import kotlin.jvm.JvmOverloads
import android.widget.RelativeLayout
import android.widget.TextView
import com.scwang.smart.refresh.layout.constant.SpinnerStyle
import com.scwang.smart.refresh.layout.api.RefreshKernel
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.constant.RefreshState
import com.xmmj.common.R
import com.scwang.smart.refresh.layout.api.RefreshHeader

@SuppressLint("RestrictedApi")
class CustomHeader @JvmOverloads constructor(context: Context?, attrs: AttributeSet? = null) :
    RelativeLayout(context, attrs, 0), RefreshHeader {

    private val threeBall: ThreeBallView

    private val tvHint: TextView?

    init {
        inflate(context, R.layout.layout_custom_header, this)
        threeBall = findViewById(R.id.iv_ball)
        tvHint = findViewById(R.id.tv_hint)
    }

    fun setHint(hint: String?) {
        if (tvHint != null && !TextUtils.isEmpty(hint)) tvHint.text = hint
    }

    override fun getView(): View {
        return this
    }

    override fun getSpinnerStyle(): SpinnerStyle {
        return SpinnerStyle.Translate
    }

    override fun setPrimaryColors(vararg colors: Int) {

    }

    override fun onInitialized(kernel: RefreshKernel, height: Int, maxDragHeight: Int) {

    }

    override fun onMoving(
        isDragging: Boolean,
        percent: Float,
        offset: Int,
        height: Int,
        maxDragHeight: Int
    ) {

    }

    override fun onReleased(refreshLayout: RefreshLayout, height: Int, maxDragHeight: Int) {

    }

    override fun onStartAnimator(refreshLayout: RefreshLayout, height: Int, maxDragHeight: Int) {

    }

    override fun onFinish(refreshLayout: RefreshLayout, success: Boolean): Int {
        return 500
    }

    override fun onHorizontalDrag(percentX: Float, offsetX: Int, offsetMax: Int) {

    }

    override fun isSupportHorizontalDrag(): Boolean {
        return false
    }

    override fun onStateChanged(
        refreshLayout: RefreshLayout,
        oldState: RefreshState,
        newState: RefreshState
    ) {
        when (newState) {
            RefreshState.None -> {
                threeBall.visibility = VISIBLE
                tvHint!!.visibility = GONE
            }
            RefreshState.PullDownToRefresh -> {}
            RefreshState.ReleaseToRefresh -> threeBall.startAnimator()
            RefreshState.RefreshReleased -> {}
            RefreshState.Refreshing -> {}
            RefreshState.RefreshFinish -> {
                threeBall.stopAnimator()
                threeBall.visibility = GONE
                tvHint!!.visibility = VISIBLE
            }
            else -> {

            }
        }
    }
}